package com.yanfan.jt808;

import com.yanfan.common.core.mq.DeviceReport;
import com.yanfan.common.core.mq.MQSendMessageBo;
import com.yanfan.common.core.mq.message.DeviceData;
import com.yanfan.common.core.mq.message.FunctionCallBackBo;
import com.yanfan.jt808.bean.BCD;
import com.yanfan.jt808.bean.DataPacket;
import com.yanfan.protocol.base.protocol.IProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
//@SysProtocol(name = "JT808解析协议", protocolCode = YanfanConstant.PROTOCOL.JT808, description = "系统内置JT808解析协议")
public class Rj45ProtocolService implements IProtocol {

    @Override
    public DeviceReport decode(DeviceData data, String clientId) {
        DataPacket msg = decode(data.getBuf());
        DeviceReport reportMessage = new DeviceReport();
        reportMessage.setThingsModelSimpleItem(null/*values*/);
        reportMessage.setSerialNumber(clientId);
        reportMessage.setClientId(clientId);
        return reportMessage;
    }

    private DataPacket decode(ByteBuf in) {
        if (in.readableBytes() < 12) { //包头最小长度
            return null;
        }
        //第一步 转义
        byte[] raw = new byte[in.readableBytes()];
        in.readBytes(raw);
        ByteBuf escape = revert(raw);
        //第二步 校验
        byte pkgCheckSum = escape.getByte(escape.writerIndex() - 1);
        escape.writerIndex(escape.writerIndex() - 1);//排除校验码
        byte calCheckSum = BCD.XorSumBytes(escape);
        if (pkgCheckSum != calCheckSum) {
            log.warn("校验码错误,pkgCheckSum:{},calCheckSum:{}", pkgCheckSum, calCheckSum);
            ReferenceCountUtil.safeRelease(escape);
            return null;
        }
        //第三步:解码
//        return parse(escape);
        return null;
    }

    @Override
    public FunctionCallBackBo encode(MQSendMessageBo message) {
        return null;
    }
	/**
	 * 将接收到的原始转义数据还原
	 *
	 * @param raw
	 * @return
	 */
	public ByteBuf revert(byte[] raw) {
		int len = raw.length;
		ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer(len);//DataPacket parse方法回收
		for (int i = 0; i < len; i++) {
			//这里如果最后一位是0x7d会导致index溢出，说明原始报文转义有误
			if (raw[i] == 0x7d && raw[i + 1] == 0x01) {
				buf.writeByte(0x7d);
				i++;
			} else if (raw[i] == 0x7d && raw[i + 1] == 0x02) {
				buf.writeByte(0x7e);
				i++;
			} else {
				buf.writeByte(raw[i]);
			}
		}
		return buf;
	}
/*

	public DataPacket parse(ByteBuf bb) {
		DataPacket packet = null;
		short msgId = bb.getShort(bb.readerIndex());
		switch (msgId) {
			case Const.TERNIMAL_MSG_HEARTBEAT:
				packet = new HeartBeatMessage(bb);
				break;
			case Const.TERNIMAL_MSG_LOCATION://0200
				packet = new LocationMessage(bb);
				break;
			case Const.TERNIMAL_MSG_LOCATION_BATCH://0704
				packet = new LocationBatchMessage(bb);
				break;
			case Const.TERNIMAL_MSG_REGISTER:
				packet = new RegisterMessage(bb);
				break;
			case Const.TERNIMAL_MSG_AUTH:
				packet = new AuthMessage(bb);
				break;
//			case Const.TERNIMAL_MSG_STATUS:     0900数据
//				packet = new StatusMessage(bb);
//				break;
			default:
				packet = new DataPacket(bb);
				break;
		}
		packet.parse();
		return packet;
	}
*/


}
